﻿using Core;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(GridLayoutGroup))]
public partial class NineGrid : MonoBehaviour
{
    public int Size = 3;

    private int GridSize = 3;
    private GridLayoutGroup m_layout;
    private float Width;
    private float Height;
    private List<Node> m_childs = new List<Node>();

    private void Awake()
    {
        m_layout = GetComponent<GridLayoutGroup>();
        var rect = GetComponent<RectTransform>().rect;
        Width = rect.width;
        Height = rect.height;

        m_childs.Clear();
        int child_cnt = transform.childCount;

        if (child_cnt == 0)
        {
            log.err($"Error! NineGridResizer至少需要一个子节点");
            return;
        }

        for (int i = 0; i < child_cnt; i++)
        {
            var child = transform.GetChild(i);
            var node = new Node();
            node.Awake(child.gameObject);
            m_childs.Add(node);
        }

        Init();
    }
    public void Init()
    {
        var Total = GridSize * GridSize;

        m_layout.childAlignment = TextAnchor.MiddleCenter;
        m_layout.constraint = GridLayoutGroup.Constraint.FixedColumnCount;
        m_layout.constraintCount = GridSize;

        var cnt = m_childs.Count;
        if (Total > cnt)
        {
            var delta = Total - cnt;
            var template = m_childs[0].Go;
            for (int i = 0; i < delta; i++)
            {
                var go = GameObject.Instantiate(template);
                go.transform.parent = transform;
                go.name = (i + cnt + 1).ToString();
                var node = new Node();
                node.Awake(go);
                m_childs.Add(node);
            }
        }
        else if (Total < cnt)
        {
            for (int i = cnt - 1; i >= Total; i--)
            {
                var node = m_childs[i];
                m_childs.RemoveAt(i);
                GameObject.DestroyImmediate(node.Go);
            }
        }

        var padding_h = m_layout.padding.left + m_layout.padding.right;
        var padding_v = m_layout.padding.top + m_layout.padding.bottom;
        var spacing_x = m_layout.spacing.x;
        var spacing_y = m_layout.spacing.y;


        var item_width = (int)((Width - padding_h - spacing_x * (Size - 1)) / Size);
        var item_height = (int)((Height - padding_v - spacing_y * (Size - 1)) / Size);

        var cell_size = Mathf.Min(item_width, item_height);
        m_layout.cellSize = new Vector2(cell_size, cell_size);

        InitChild();
    }

    private void InitChild()
    {
        foreach (var child in m_childs)
        {
            child.InitGrid(Size, m_layout.cellSize);
        }
    }
}
